<?php

function isPhone($phone) {
    return !!preg_match('/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$|(^1[3|4|5|7|8]\d{9}$)|(^[1|9]\d{4}$)|(^400-?\d{3}-?\d{4})/', $phone);
}

function isMobile($string) {
    return !!preg_match('/^1[3|4|5|7|8]\d{9}$/', $string);
}

function isInMobile(){
    if (stristr($_SERVER['HTTP_VIA'], "wap")) {
        return true;
    } elseif (strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML") > 0) {
        return true;
    } elseif (preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
        return true;
    } else {
        return false;
    }
}

function isEmail($string) {
    return !!preg_match('/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/i', $string);
}

function isUserName($string) {
    return !!preg_match('/^[a-zA-z][a-zA-Z0-9_]{1,15}$/', $string);
}

function encrypt($str, $key) {
    $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
    $str = pkcs5Pad($str, $size);

    $data = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
    return base64_encode($data);
}

//解密
function decrypt($str, $key) {
    $str = base64_decode($str);
    $str = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_DECRYPT, $key);
    $str = pkcs5Unpad($str);
    return $str;
}

function pkcs5Pad($text, $blocksize) {
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5Unpad($text) {
    $pad = ord($text{strlen($text) - 1});
    if ($pad > strlen($text))
        return false;
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
        return false;
    return substr($text, 0, -1 * $pad);
}

function format_time($time, $hms = true) {
    if (!$time)
        return;
    $format = $hms ? 'Y-m-d H:i:s' : 'Y-m-d';
    return date($format, $time);
}

function ajax_return($status = 1, $message = '', $extend = []) {
    $data = [
        'status' => $status ? 'success' : 'failed',
        'message' => $message,
    ];
    if (!empty($extend)) {
        $data = array_merge($data, $extend);
    }
    exit(json_encode($data));
}

function tips($string) {
    echo '<span class="tips" data-title="' . $string . '"><i class="icon iconfont">&#xe620;</i></span>';
}

function details($string) {
    echo '<span class="tips" data-title="' . urlencode($string) . '"><i class="icon iconfont">&#xe621;</i></span>';
}

//
function setting_text($key, $val) {
    $setting = C($key);
    if ($setting && isset($setting[$val])) {
        return $setting[$val];
    } else {
        return '未知';
    }
}

//日期格式是否正确
function is_date($date) {
    list($year, $month, $day) = explode('-', $date);
    return checkdate(intval($month), intval($day), intval($year));
}

/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $length = 0, $suffix = '', $charset = "utf-8") {
    if ($length == 0) {
        return $str;
    }
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, 0, $length, $charset);
    elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, 0, $length, $charset);
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], 0, $length));
    }
    return ($slice == $str) ? $slice : $slice . $suffix;
}

/**
 * 字符串截取,修正
 */
function str_cut($str, $start = 0, $length = 0, $charset = 'utf-8') {
    if ($length == 0) {
        return $str;
    }
    if (function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
    } else {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
    }
    return $slice;
}

/**
 * 获取字符串长度,支持中文
 */
function mstrlen($str) {
    if (empty($str)) {
        return 0;
    }
    if (function_exists('mb_strlen')) {
        return mb_strlen($str, 'utf-8');
    } else {
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}

/**
 * 加密密码
 */
function entrypt_password($password, $key = 'c-54a5') {
    return md5(md5($password) . $key);
}

//数字转汉字
function num2char($num, $mode = true) {
    $char = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
    //$char = array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖);
    $dw = array('', '十', '百', '千', '', '万', '亿', '兆');
    //$dw = array('','拾','佰','仟','','萬','億','兆');
    $dec = '点';  //$dec = '點';
    $retval = '';
    if ($mode) {
        preg_match_all('/^0*(\d*)\.?(\d*)/', $num, $ar);
    } else {
        preg_match_all('/(\d*)\.?(\d*)/', $num, $ar);
    }
    if ($ar[2][0] != '') {
        $retval = $dec . ch_num($ar[2][0], false); //如果有小数，先递归处理小数
    }
    if ($ar[1][0] != '') {
        $str = strrev($ar[1][0]);
        for ($i = 0; $i < strlen($str); $i++) {
            $out[$i] = $char[$str[$i]];
            if ($mode) {
                $out[$i] .= $str[$i] != '0' ? $dw[$i % 4] : '';
                if ($str[$i] + $str[$i - 1] == 0) {
                    $out[$i] = '';
                }
                if ($i % 4 == 0) {
                    $out[$i] .= $dw[4 + floor($i / 4)];
                }
            }
        }
        $retval = join('', array_reverse($out)) . $retval;
    }
    return $retval;
}

/**
 * 动态加密解密
 * @param string $string 要操作的字符串
 * @param string $operation 操作类型
 * @param string $key 密钥
 * @expiry int $expiry 有效期
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key != '' ? $key : md5('liuxinglei'));
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

/**
 * 格式化时间
 */
function visual_time($time = '') {
    $time = intval($time);
    if ($time) {
        $timeC = time() - $time;
    } else {
        $timeC = 0;
    }
    if ($timeC < 60) {
        $return = "刚刚";
    } else if ($timeC < 3600) {
        $return = intval($timeC / 60) . '分钟前';
    } elseif ($timeC < 86400) {
        $return = intval($timeC / 3600) . '小时前';
    } elseif ($timeC < 86400 * 30) {
        $return = intval($timeC / 84600) . '天前';
    } else {
        $return = date('Y-m-d', $time);
    }
    return $return;
}

/**
 * 返回自动缩略图地址格式
 */
function image($img, $width = 200, $height = 200) {
    if ($img == '') {
        return "/Upload/nopic.jpg";
    }
    $img_info = parse_url($img);
    /* 外部链接直接返回图片地址 */
    if (!empty($img_info['host']) && $img_info['host'] != $_SERVER['HTTP_HOST']) {
        return $img;
    } else {
        $pos = strrpos($img, '.');
        $img = substr($img, 0, $pos) . '_' . $width . '_' . $height . substr($img, $pos);
        return $img;
    }
}

/**
 * 检测是否为身份证号码
 */
function isIdcard($id_card) {
    if (strlen($id_card) == 18) {
        return idcard_checksum18($id_card);
    } elseif ((strlen($id_card) == 15)) {
        $id_card = idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    } else {
        return false;
    }
}

function idcard_verify_number($idcard_base) {
    if (strlen($idcard_base) != 17) {
        return false;
    }
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);

    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++) {
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }
    $mod = $checksum % 11;
    $verify_number = $verify_number_list[$mod];
    return $verify_number;
}

function idcard_15to18($idcard) {
    if (strlen($idcard) != 15) {
        return false;
    } else {
        if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
            $idcard = substr($idcard, 0, 6) . '18' . substr($idcard, 6, 9);
        } else {
            $idcard = substr($idcard, 0, 6) . '19' . substr($idcard, 6, 9);
        }
    }
    $idcard = $idcard . idcard_verify_number($idcard);
    return $idcard;
}

function idcard_checksum18($idcard) {
    if (strlen($idcard) != 18) {
        return false;
    }
    $idcard_base = substr($idcard, 0, 17);
    if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))) {
        return false;
    } else {
        return true;
    }
}

/**
 * 过滤XSS 注入
 */
function remove_xss($val) {

    $val = preg_replace('/([\x00-\x08\x0b-\x0c\x0e-\x19])/', '', $val);
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
        $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
    }
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);
    $found = true;
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
            $val = preg_replace($pattern, $replacement, $val);
            if ($val_before == $val) {
                $found = false;
            }
        }
    }
    return $val;
}

/**
 * 发送短信
 */
function send_sms($mobile, $content) {
    return file_get_contents("http://61.191.26.181:8888/SmsPort.asmx/SendSms?epid=886&User_Name=shequ&password=" . substr(md5('xc234oc!@#'), 8, 16) . "&phone=" . $mobile . "&content=" . urlencode($content));
}

//获取周几
function get_week($date, $pre = "星期") {
    $str = ['日','一','二','三','四','五','六'];
    $week = date('w', $date);
    return $pre . $str[$week];
}

//判断为1或者0
function tinyintval($number, $default = 0) {
    if (!in_array(intval($number), [0, 1])) {
        return $default;
    }
    return intval($number);
}

/**
 * 将字符串转换为数组
 *
 * @param    string $data 字符串
 * @return    array    返回数组格式，如果，data为空，则返回空数组
 */
function string2array($data) {
    if ($data == '') {
        return array();
    }
    $str = substr($data, 0, 1);
    if ($str == 'a') {
        $array = unserialize($data);
    } else if ($str == '{') {
        $data = stripslashes($data);
        @eval("\$array = $data;");
    }
    return $array;
}

/**
 * 将数组转换为字符串
 *
 * @param    array $data 数组
 * @param    bool $isformdata 如果为0，则不使用new_stripslashes处理，可选参数，默认为1
 * @return    string    返回字符串，如果，data为空，则返回空
 */
function array2string($data) {
    if ($data == '')
        return '';
    return serialize($data);
}

/**
 * 解析数组为参数格式
 */
function parse_array($array) {
    if (empty($array)) {
        return '';
    }
    foreach ($array as $key => $val) {
        $param[] = $key . '=' . $val;
    }
    return implode('&', $param);
}

/**
 * 解析字符串为数组
 */
function parse_string($string) {
    if (strlen($string) === 0) {
        return array();
    }
    $return = array();
    foreach (explode('&', $string) as $str) {
        list($name, $value) = explode('=', $str);
        $return[$name] = $value;
    }
    return $return;
}

/**
 * 无限级分类树形结构
 */
function tree_array($data) {
    usort($data, 'sort_by_pid');
    $result = array();
    $I = array();
    foreach ($data as $val) {
        if ($val['pid'] == 0) {
            $i = count($result);
            $result[$i] = $val;
            $I[$val['id']] = &$result[$i];
        } else {
            $i = count($I[$val['pid']]['child']);
            $I[$val['pid']]['child'][$i] = $val;
            $I[$val['id']] = &$I[$val['pid']]['child'][$i];
        }
    }
    sort_tree($result);
    return $result;
}

/**
 * 树形数据排序
 */
function sort_tree(&$data) {
    usort($data, 'sort_by_fun');
    foreach ($data as &$val) {
        if ($val['child']) {
            sort_tree($val['child']);
        }
    }
}

/**
 * 树形数据排序
 */
function sort_by_fun($a, $b) {
    if ($a['sort'] == $b['sort']) {
        return $a['id'] > $b['id'] ? 1 : -1;
    }
    return $a['sort'] < $b['sort'] ? -1 : 1;
}

/**
 * 树形数据排序
 */
function sort_by_pid($a, $b) {
    if ($a['pid'] == $b['pid']) {
        if (isset($a['sort'])) {
            return $a['sort'] > $b['sort'] ? 1 : -1;
        } else {
            return $a['id'] > $b['id'] ? 1 : -1;;
        }
    }
    return $a['pid'] < $b['pid'] ? -1 : 1;
}

/**
 * 获取当前ID 的所有下属子ID 无限级
 */
function tree_childs($data, $ids, $return = array()) {
    if (!is_array($ids)) {
        $ids = array($ids);
    }
    $find = false;
    foreach ($data as $key => $val) {
        if (in_array($val['pid'], $ids)) {
            $return[] = $key;
            $find = true;
            unset($data[$key]);
        }
    }
    if ($find == true) {
        $return = tree_childs($data, $return, $return);
    }
    return $return;
}

/**
 * 二维数组查找是否有某个值
 */
function field_in_array($field, $value, $array) {
    foreach ($array as $val) {
        if ($val[$field] == $value) {
            return true;
        }
    }
    return false;
}

/**
 * 数组字符串转义
 */
function daddslashes($string, $force = 1) {
    if (is_array($string)) {
        $keys = array_keys($string);
        foreach ($keys as $key) {
            $val = $string[$key];
            unset($string[$key]);
            $string[addslashes($key)] = daddslashes($val, $force);
        }
    } else {
        $string = addslashes($string);
    }
    return $string;
}

/**
 * 解析TAG 推荐位
 */
function parse_tags($tag) {
    $tag = intval($tag);
    $tags = array();
    $i = 1;
    $total = 0;
    while (true) {
        $k = pow(2, $i - 1);
        $total += $k;
        if ($tag & $k) {
            $tags[] = $i;
        }
        if ($total >= $tag) {
            break;
        }
        $i++;
    }
    return $tags;
}

//format fields (array,string) =>  a,b,c  mysql 用的字段field(a,c,b)
function format_fields($fields, $alias = '') {
    $return = '';
    if (!empty($alias)) {
        $return = $alias . '.';
    }

    if (empty($fields) || $fields == '*') {
        return $return . $fields;
    }

    if (is_array($fields)) {
        $fields = implode(',', $return . $fields);
    } else {
        $fields = trim($fields, ',');
        $fields = explode(',', $fields);
        $fields = implode(',', $return . $fields);
    }
    return $fields;
}

//0-冻结身份 9-普通用户 69-联盟商家 99-运营中心  109-顶级运营中心
function userIdentity($key) {
    $identity = '';
    switch ($key) {
        case 0:
            $identity = '未审核用户';
            break;
        case 9:
            $identity = '普通用户';
            break;
        case 69:
            $identity = '联盟商家';
            break;
        case 99:
            $identity = '运营中心';
            break;
        case 109:
            $identity = '总运营中心';
            break;
        default:
            $identity = '未知身份';
            break;
    }

    return $identity;
}

function applyStatus($status) {
    $result = '';
    switch ($status) {
        case 0:
            $result = '等待处理';
            break;
        case 1:
            $result = '已拒绝';
            break;
        case 2:
            $result = '已通过';
            break;
        default:
            $result = '未处理';
    }
    return $result;
}

//支付方式
if(!function_exists('payTypes')){
    function payTypes($type){
        $result = '';
        switch ($type) {
            case 1:
                $result = '全额现金';
                break;
            case 2:
                $result = '现金+积分';
                break;
            default:
                $result = '全额现金';
        }
        return $result;
    }
}

//用户流水记录表
if(!function_exists('userAccountType')){
    function userAccountType($type){
        $result ='';
        switch ($type){
            case 0:
                $result = '现金';
                break;
            case 1:
                $result = '可用积分';
                break;
            case 2:
                $result = '待用积分';
                break;
            case 3:
                $result = '商品券';
                break;
            default:
                $result = '积分';
                break;
        }
        return $result;
    }
}

if(!function_exists('orderStatus')){
    function orderStatus($type){
        $result ='';
        switch ($type){
            case 0:
                $result = '待付款';
                break;
            case 1:
                $result = '待发货';
                break;
            case 2:
                $result = '待收货';
                break;
            case 3:
                $result = '待评价';
                break;
            case 4:
                $result = '已评价';
                break;
            case 5:
                $result = '已取消';
                break;
            case 6:
                $result = '订单退货';
                break;
            default:
                $result = '';
                break;
        }
        return $result;
    }
}

if(!function_exists('createOrderId()')){
    function createOrderId(){
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}